﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApiCoreDemo.Model;

namespace WebApiCoreDemo.Api.Controllers
{
    [Authorize]
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class AuthorizeController : ControllerBase
    {
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Get()
        {
            return new ObjectResult(new ResponseResult
            {
                Success = false,
                Data = "未授权"
            });
        }

        [HttpGet]
        public IActionResult GetInfo()
        {
            #region 获取BearerToken方法1
            //var name = base.HttpContext.AuthenticateAsync().Result.Principal.Claims.FirstOrDefault(a => a.Type.Equals("Name"))?.Value; 
            #endregion

            #region 获取BearerToken方法2
            var name = ((ClaimsIdentity)User.Identity).Name;
            string id = ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(claim => claim.Type.Equals("Id"))?.Value;
            string role = ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(claim => claim.Type.Equals("Role"))?.Value; 
            #endregion

            return new ObjectResult(new ResponseResult
            {
                Success = true,
                Data = "[" + name + "/" + id + "/" + role + "]已授权"
            });
        }
    }
}